// mediaCache.js
import StorageCache from '@/common/mediacache/index.js';
import upload from '@/common/upload/upload.js'
class MediaCache {
  constructor() {
    this.cache = new Map();
    this.queue = new Map();
  }

  isLocalPath(path) {
    // 使用正则表达式匹配以"/"、"file:/"或"_doc/"开头的路径
    return /^\/|^file:\/|^_doc\//i.test(path);
  }

  extractBaseUrl(url) {
    const parts = url.split('?');
    return parts.length ? parts[0] : '';
  }

  async fetchMediaUrl(srckey, uploadType) {
    return new Promise((resolve, reject) => {
	  upload.seeFile(srckey,uploadType).then(res=>{
		  resolve(res.Url);
	  }).catch(reject);
    });
  }
// image_chat_cache_list
  async downloadAndCacheMedia(srckey, url, localKey, fileTpye) {
    return new Promise((resolve, reject) => {
	  if(fileTpye == 'video'){
		  resolve(url);
	  }
	  console.log('开始下载',url);
      uni.downloadFile({
        url,
        success: async (res) => {
          if (res.statusCode === 200) {
            try {
              const savedFilePath = await this.saveFile(res.tempFilePath);
              StorageCache.setCachedUrl(localKey, srckey, savedFilePath);
              resolve(savedFilePath);
            } catch (e) {
              reject(e);
            }
          } else {
            reject(new Error('Media download error'));
          }
        },
        fail: reject
      });
    });
  }

  saveFile(tempFilePath) {
    return new Promise((resolve, reject) => {
      uni.saveFile({
        tempFilePath,
        success: (res) => {
          resolve(res.savedFilePath);
        },
        fail: reject
      });
    });
  }

  isValidCache(url) {
    // Implement your cache validation logic (if needed)
    return true;
  }
// image_chat_cache_list
  loadMedia(srckey, uploadType, fileTpye) {
    return new Promise((resolve, reject) => {
	  if(!srckey){
		  reject('Media Key null')
		  return
	  }
      if (this.isLocalPath(srckey)) {
        resolve(srckey);
        return;
      }
	  let localKey = `${fileTpye}_${uploadType}_cache_list`
      const cachedUrl = StorageCache.getCachedUrl(localKey, srckey);
      if (cachedUrl && this.isValidCache(cachedUrl)) {
        resolve(cachedUrl);
      } else {
        if (this.queue.has(srckey)) {
          this.queue.get(srckey).push({ resolve, reject });
        } else {
          this.queue.set(srckey, [{ resolve, reject }]);
          this.fetchMediaUrl(srckey, uploadType)
            .then(url => {
				return this.downloadAndCacheMedia(srckey, url, localKey, fileTpye)
			}).then(filePath => {
				console.log(filePath);
			  // 遍历队列中的所有请求，调用它们的 resolve 回调函数
			  this.queue.get(srckey).forEach(p => p.resolve(filePath));
			  // 清理队列
			  this.queue.delete(srckey);
            })
            .catch(error => {
              // 遍历队列中的所有请求，调用它们的 reject 回调函数
			  this.queue.get(srckey).forEach(p => p.reject(error));
			  // 清理队列
			  this.queue.delete(srckey);
            });
        }
      }
    });
  }
}

export default new MediaCache();
